// 数据库操作
const mongoose = require("mongoose");
// 对象规则验证
const Joi = require("joi");

// 模型规则类
const { Schema } = mongoose;

const EntitySchema = new Schema(
  {
    entityName: {
      type: String,
      required: true,
      unique: true,
    },
    description: {
      type: String,
      required: true,
    },
    owners: {
      type: Array,
    },
    fields: {
      type: String,
      required: true,
    },
    indexs: {
      type: String,
      required: true,
    },
    modifyTime: {
      type: String,
      default: Date.now,
    },
  },
  { versionKey: false }
);

const Entity = mongoose.model("Entity", EntitySchema);

// 定义对象验证规则
const entityRules = {
  entityName: Joi.string().required().error(new Error("entityName 是必需的")),
  description: Joi.string().required().error(new Error("description 是必需的")),
  fields: Joi.string().required().error(new Error("fields 是必需的")),
  indexs: Joi.string().required().error(new Error("indexs 是必需的")),
};

// 注册数据格式校验
const validateEntity = (entity) => {
  return Joi.validate(entity, entityRules, {
    // 检测到所有错误
    abortEarly: false,
    // 允许对象包含被忽略的未知键
    allowUnknown: true,
  });
};

// 导出对象
module.exports = {
  Entity,
  entityRules,
  validateEntity,
};
